<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2>系统登录</h2>
      </template>
      
      <!-- 登录方式切换 -->
      <el-tabs v-model="loginType" @tab-click="handleTabClick">
        <el-tab-pane label="账号密码登录" name="2">
          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            label-width="0"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                :prefix-icon="User"
                clearable
                @keyup.enter="focusPassword"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                ref="passwordRef"
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                :prefix-icon="Lock"
                show-password
                clearable
                @keyup.enter="focusCaptcha"
              />
            </el-form-item>
            <el-form-item prop="result">
              <div class="captcha-container">
                <el-input
                  ref="captchaRef"
                  v-model="loginForm.result"
                  placeholder="请输入验证码"
                  :prefix-icon="Key"
                  @keyup.enter="handleLogin"
                />
                <img 
                  :src="captchaImg" 
                  alt="验证码" 
                  class="captcha-img"
                  @click="refreshCaptcha"
                />
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="手机号登录" name="1">
          <el-form
            ref="phoneFormRef"
            :model="phoneForm"
            :rules="phoneRules"
            label-width="0"
          >
            <el-form-item prop="number">
              <el-input
                v-model="phoneForm.number"
                placeholder="请输入手机号"
                :prefix-icon="Iphone"
                clearable
                @keyup.enter="focusPhoneCode"
              />
            </el-form-item>
            <el-form-item prop="result">
              <div class="captcha-container">
                <el-input
                  ref="phoneCodeRef"
                  v-model="phoneForm.result"
                  placeholder="请输入验证码"
                  :prefix-icon="Key"
                  @keyup.enter="handleLogin"
                />
                <el-button 
                  type="primary" 
                  :disabled="!!countdown"
                  @click="sendSmsCode"
                >
                  {{ countdown ? `${countdown}s后重新获取` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <el-button 
        type="primary" 
        :loading="loading" 
        @click="handleLogin" 
        block
      >
        {{ loading ? '登录中...' : '登录' }}
      </el-button>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { User, Lock, Key, Iphone } from '@element-plus/icons-vue'
import { login, getCaptcha, initMenu } from '@/api/user'
import type { LoginDTO } from '@/api/user'

const router = useRouter()
const loginType = ref<'1' | '2'>('2')
const loading = ref(false)
const captchaImg = ref('')
const uuid = ref('')
const countdown = ref(0)
let timer: number

// 账号密码登录表单
const loginFormRef = ref<FormInstance>()
const passwordRef = ref<any>()
const captchaRef = ref<any>()
const loginForm = reactive({
  username: '',
  password: '',
  result: '',
  type: '2' as const
})

// 手机号登录表单
const phoneFormRef = ref<FormInstance>()
const phoneCodeRef = ref<any>()
const phoneForm = reactive({
  number: '',
  result: '',
  type: '1' as const
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码长度为 4 位', trigger: 'blur' }
  ]
}

const phoneRules = {
  number: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度为 6 位', trigger: 'blur' }
  ]
}

// 获取图形验证码
const refreshCaptcha = async () => {
  try {
    const res = await getCaptcha()
    if (res.code === 200) {
      captchaImg.value = res.data
      uuid.value = res.msg || ''  // 添加空字符串作为默认值
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

// 发送短信验证码
const sendSmsCode = async () => {
  if (!phoneForm.number) {
    ElMessage.warning('请先输入手机号')
    return
  }
  
  // TODO: 调用发送短信验证码接口
  countdown.value = 60
  timer = window.setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(timer)
    }
  }, 1000)
}

// 输入框焦点控制
const focusPassword = () => {
  passwordRef.value?.focus()
}

const focusCaptcha = () => {
  captchaRef.value?.focus()
}

const focusPhoneCode = () => {
  phoneCodeRef.value?.focus()
}

// 切换登录方式
const handleTabClick = () => {
  loginForm.result = ''
  phoneForm.result = ''
}

// 处理登录
const handleLogin = async () => {
  const currentForm = loginType.value === '2' ? loginFormRef.value : phoneFormRef.value
  const formData = loginType.value === '2' ? loginForm : phoneForm
  
  if (!currentForm) return
  
  try {
    const valid = await currentForm.validate()
    if (valid) {
      loading.value = true
      
      try {
        const loginData: LoginDTO = {
          ...formData,
          code: uuid.value
        }
        
        const res = await login(loginData)
        if (res.code === 200) {
          // 保存 token
          localStorage.setItem('token', res.data)
          
          // 获取菜单数据
          try {
            const menuRes = await initMenu()
            if (menuRes.code === 200) {
              // 可以将菜单数据保存到 localStorage 或 Pinia store 中
              localStorage.setItem('menuList', JSON.stringify(menuRes.data))
              ElMessage.success('登录成功')
              router.push('/dashboard')
            } else {
              ElMessage.error('获取菜单失败')
            }
          } catch (error) {
            console.error('获取菜单失败:', error)
            ElMessage.error('获取菜单失败')
          }
        }
      } catch (error: any) {
        ElMessage.error(error.message || '登录失败，请重试')
        if (loginType.value === '2') {
          refreshCaptcha()
        }
      } finally {
        loading.value = false
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

onMounted(() => {
  refreshCaptcha()
})

onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  
  .login-card {
    width: 400px;
    margin-top: -100px;
    
    :deep(.el-tabs__nav) {
      width: 100%;
      
      .el-tabs__item {
        width: 50%;
        text-align: center;
      }
    }
    
    .captcha-container {
      display: flex;
      gap: 12px;
      
      .el-input {
        flex: 1;
      }
      
      .captcha-img {
        height: 32px;
        cursor: pointer;
      }
      
      .el-button {
        width: 120px;
      }
    }
    
    .el-button {
      margin-top: 20px;
    }
  }
}
</style> 